package com.yjq.blog.article.service.impl;

import com.yjq.blog.article.service.CometService;
import com.yjq.blog.article.utils.CometPullTask;
import com.yjq.blog.article.utils.CometPushTask;
import org.springframework.stereotype.Service;

import javax.servlet.AsyncContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Service
public class CometServiceImpl implements CometService {

    private final ScheduledExecutorService scheduler;
    private final Map<String, CometPullTask> cometTasks;

    public CometServiceImpl() {
        scheduler = new ScheduledThreadPoolExecutor(1);
        cometTasks = new HashMap<>();
    }

    @Override
    public void receiveMessage(String sessionId, HttpServletRequest req, HttpServletResponse resp) {
        final AsyncContext asyncContext = req.startAsync();
        scheduler.execute(new CometPullTask(cometTasks, scheduler, asyncContext, sessionId, req, resp));
    }

    @Override
    public void sendMessage(String sessionId, String data) {
        scheduler.schedule(new CometPushTask(sessionId, data, cometTasks), 0L, TimeUnit.MILLISECONDS);
    }

}
